package com.dk.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

//核心配置类
@Configuration
public class ShiroConfig {

    //创建过滤器工厂类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean =new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        //粒度 (粗,细)
        //过滤器链 1.anon : 无需登录就可以访问 2. authc: 必须登录才能访问 3.perms: 登录后必须授权才能访问 role: 登录后必须有这个角色才能访问
        //4.logout 退出登录
        Map<String,String> map= new LinkedHashMap<>();// 存取有序 linked 单链表

        map.put("/user/login","anon");
        //放过登录方法
        map.put("/menu/toShow","perms[menu:show]");//permissins
       // map.put("/role/toShow","perms[role:list]");//permissins
        map.put("/role/toAdd","perms[role:add]");//permissins
        map.put("/user/toShow","perms[user:list]");//permissins

        //退出登录
        map.put("/logout","logout");

        map.put("/**","authc");

        //设置跳转登录页面
        factoryBean.setLoginUrl("/user/toLogin");
        factoryBean.setUnauthorizedUrl("/unauthorized");
        //设置过滤器链
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

    //创建安全管理器SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired  LoginUserRealm loginUserRealm){
        DefaultWebSecurityManager securityManager =new DefaultWebSecurityManager();
        securityManager.setRealm(loginUserRealm);
        return securityManager;
    }

    @Bean
    public LoginUserRealm loginUserRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginUserRealm loginUserRealm =new LoginUserRealm();
        //设置shiro的加密方式
        loginUserRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginUserRealm;
    }
    //密码加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置密码
        matcher.setStoredCredentialsHexEncoded(true);
        //加密迭代的次数 1234 aaaa bbbb
        matcher.setHashIterations(5);
        //加密方式
        matcher.setHashAlgorithmName("MD5");
        return matcher;
    }
    //开启thymeleaf整合shiro功能
    @Bean
    public ShiroDialect shiroDialect(){

        return new ShiroDialect();
    }
}
